package org.abettor.nookinfo.novel;

import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.modal.Pair;
import org.abettor.nookinfo.persist.NovelHelper;
import org.abettor.nookinfo.persist.NovelHelper.LastRead;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 文章段落类
 * @author abettor
 *
 */
public class NovelContent extends Activity
{
	public static final String NOVEL_CONTENT_ID = "NOVEL_CONTENT_ID";
	private static final int REFRESHED = 1;//文章更新已完成事件
	private static final int FAILED = 2;//文章更新失败时间
	private static final int MENU_PREV = Menu.FIRST + 1;
	private static final int MENU_NEXT = MENU_PREV + 1;
	private static final int MENU_REFRESH = MENU_NEXT + 1;
	private static final int MENU_CLOSE = MENU_REFRESH + 1;
	private YoumiManager youmi = new YoumiManager(this);
	private NovelHelper novelHelper = new NovelHelper(this);
	private int content;
	private String novelName;
	private String novelCategoryName;
	private ActionType actionType = ActionType.refresh;
	private ProgressDialog progressDialog = null;//进度条对话框
	private Worker worker = null;//网络访问线程
	private Handler handler = new Handler()
	{
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESHED)
			{
				//	更新内容页，并重新设定当前章节ID
				Pair<String, String> pair = (Pair<String, String>) msg.obj;
				content = Integer.parseInt(pair.first);
				TextView textView = (TextView) findViewById(R.id.novelContentText);
				textView.setText(pair.second.trim());
				ScrollView scroll = (ScrollView) findViewById(R.id.novelContentScroll);
				scroll.scrollTo(0, 0);

				//	按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 20)
				{
					youmi.showYoumi(YoumiManager.Position.middle, Color.WHITE, Color.BLACK, 0xAA);
				}

				//	记录最近访问历史
				LastRead lastRead = new LastRead();
				lastRead.category = novelCategoryName;
				lastRead.id = content;
				lastRead.local = false;
				lastRead.novel = novelName;
				novelHelper.setLastRead(lastRead);
			}
			else if(msg.what == FAILED)
			{
				Builder builder = new Builder(NovelContent.this);
				builder.setTitle(R.string.novel_content_fail_title);
				builder.setMessage(R.string.novel_content_fail_content);
				builder.setPositiveButton(R.string.novel_content_fail_btn_ok, new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialoginterface, int i)
					{
						dialoginterface.dismiss();
					}
				});
				builder.show();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.novel_content);
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		content = extras.getInt(NOVEL_CONTENT_ID);
		novelName = extras.getString(NovelChapter.NOVEL_NAME);
		novelCategoryName = extras.getString(NovelList.NOVEL_CATEGORY_NAME);
		String label = getString(R.string.novel_content_label);
		label = label.replace("REPL_CATE", novelCategoryName).replace("REPL_NAME", novelName);
		setTitle(label);
		onRefreshClicked(null);
	}

	/**
	 * 创建Menu菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_PREV, MENU_PREV, getString(R.string.global_menu_prev)).setIcon(R.drawable.global_menu_prev);
		menu.add(0, MENU_NEXT, MENU_NEXT, getString(R.string.global_menu_next)).setIcon(R.drawable.global_menu_next);
		menu.add(0, MENU_REFRESH, MENU_REFRESH, getString(R.string.global_menu_refresh)).setIcon(R.drawable.global_menu_refresh);
		menu.add(0, MENU_CLOSE, MENU_CLOSE, getString(R.string.global_menu_close)).setIcon(R.drawable.global_menu_close);

		return result;
	}

	/**
	 * 处理菜单事件
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
		case MENU_PREV:
			onPrevClicked(null);
			break;
		case MENU_NEXT:
			onNextClicked(null);
			break;
		case MENU_REFRESH:
			onRefreshClicked(null);
			break;
		case MENU_CLOSE:
			onRetrunClicked(null);
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * “刷新”按钮事件方法
	 * @param v
	 */
	public void onRefreshClicked(View v)
	{
		updateContent(ActionType.refresh);
	}

	/**
	 * “返回”按钮事件方法
	 * @param v
	 */
	public void onRetrunClicked(View v)
	{
		finish();
	}

	/**
	 * “上一页”按钮事件方法
	 * @param v
	 */
	public void onPrevClicked(View v)
	{
		updateContent(ActionType.prev);
	}

	/**
	 * “下一页”按钮事件方法
	 * @param v
	 */
	public void onNextClicked(View v)
	{
		updateContent(ActionType.next);
	}

	//	更新页面内容
	private void updateContent(ActionType type)
	{
		actionType = type;
		worker = new Worker();
		worker.start();
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setTitle(R.string.novel_content_progress_title);
		progressDialog.setMessage(getText(R.string.novel_content_progress_content));
		progressDialog.setButton(getText(R.string.novel_content_progress_btn_cancel), new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialoginterface, int i)
			{
				worker.kill();
			}
		});
		progressDialog.show();
		synchronized (worker)
		{
			worker.notify();
		}
	}

	/**
	 * 读取文章章节列表的工作线程类
	 * @author abettor
	 *
	 */
	private class Worker extends Thread
	{
		//	线程是否为意外退出的标记
		private boolean cancel = false;

		/**
		 * 强制杀死工作者线程
		 */
		public void kill()
		{
			cancel = true;
			this.interrupt();
		}

		@Override
		public void run()
		{
			try
			{
				//	等待对话框创建完成
				synchronized (this)
				{
					wait();
				}

				//	此处访问网络并获取文章内容
				Pair<String, String> novelContent = fetchContent();

				//	关闭进度对话框并通知界面更新
				progressDialog.dismiss();
				if(! cancel)
				{
					//	在非意外中断情况下才更新界面
					Message msg = new Message();
					msg.what = REFRESHED;
					msg.obj = novelContent;
					handler.sendMessage(msg);
				}
				else
				{
					//	意外中断的情况下，显示错误对话框
					Message msg = new Message();
					msg.what = FAILED;
					handler.sendMessage(msg);
				}
			}
			catch (Exception e)
			{
				//	意外中断的情况下，显示错误对话框
				try { progressDialog.dismiss(); } catch (Exception ex) { };
				Message msg = new Message();
				msg.what = FAILED;
				handler.sendMessage(msg);
				Log.d(this.getClass().getName(), "", e);
			}
		}

		//	获取文章内容
		private Pair<String, String> fetchContent() throws Exception
		{
			Pair<String, String> pair = new Pair<String, String>();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			String action = null;
			switch(actionType)
			{
				case refresh:
					action = "content";
					break;
				case prev:
					action = "content-before";
					break;
				case next:
					action = "content-behind";
					break;
			}
			String url = AddressConstant.NOVEL_CONTENT.replace("ACTION", action).replace("ID", content + "");
			Document doc = db.parse(url);
			pair.first = doc.getElementsByTagName("id").item(0).getTextContent();
			pair.second = "";
			Node contentNode = doc.getElementsByTagName("value").item(0);
			NodeList contents = contentNode.getChildNodes();
			int size = contents.getLength();
			for(int i = 0; i < size; i ++)
			{
				Node node = contents.item(i);
				if(node instanceof CDATASection)
				{
					CDATASection cdata = (CDATASection) node;
					pair.second = cdata.getData();
					break;
				}
			}
			return pair;
		}
	}

	//	动作类型枚举
	private enum ActionType
	{
		refresh,
		prev,
		next;
	}
}
